package com.example.idlefish.MyAccount.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.*
import android.util.*
import android.widget.Toast
import androidx.appcompat.app.*
import com.example.idlefish.*
import com.example.idlefish.GoodsInfo.ActivityContract.PickPhotoActivityContract
import com.example.idlefish.MyAccount.contract.LoginContract
import com.example.idlefish.MyAccount.pojo.*
import com.example.idlefish.PublicModule.*
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.PublicModule.*
import com.example.idlefish.PublicModule.ApplicationConst.getBitmapFromUri
import com.example.idlefish.PublicModule.ApplicationConst.uploadAvatarImage
import com.example.idlefish.databinding.*
import com.fasterxml.jackson.databind.*
import com.google.gson.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.*
import java.util.Calendar


class MeInformationActivity: AppCompatActivity()  {
    private lateinit var binding: MyaccountInformationBinding
    private val client = OkHttpClient()
    // private val id = CommonUtil.getSerializable(intent, "id", Int::class.java)
    private val mapper = ObjectMapper()
    private val handler = Handler(Looper.getMainLooper())
    private val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    private val message = Message()
    private var  tepAvater:Bitmap? = null
    private var userHomepageInfo : UserHomepageInfo? = null
    private var pickPhotoLauncher = registerForActivityResult(PickPhotoActivityContract()){
            result->
        if(result != Uri.EMPTY)
        {
            val bitmap = getBitmapFromUri(this, result)
            tepAvater = bitmap
            binding.avatar.setImageBitmap(tepAvater)
        }
    }
    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = MyaccountInformationBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(findViewById(R.id.toolbar))

        // val userHomepageInfo = CommonUtil.getSerializable(intent, "userHomepageInfo", UserHomepageInfo::class.java)

        if(UserConst.avatarImage != null)
        {
            binding.avatar.setImageBitmap(UserConst.avatarImage)
        }
        // 初始化信息
        binding.nickname.setText(UserConst.nickname)
        binding.introduction.setText(UserConst.intro)
        if (UserConst.sex == 1) {
            binding.sex.setText("男")
        } else {
            binding.sex.setText("女")
        }

        binding.avatar.setOnClickListener {
            pickPhotoLauncher.launch(Unit)
        }

        // 切换用户
/*         binding.switchUser.setOnClickListener {
            loginLauncher.launch(123)
        } */

        // 提交信息
        binding.informationSubmit.setOnClickListener {
            val nickname = binding.nickname.text.toString()
            val intro = binding.introduction.text.toString()

            var sex = binding.sex.text.toString()
            sex = if (sex != "男" && sex != "女") {
                Toast.makeText(applicationContext, "性别请输入\"男\"或者\"女\"", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            } else if (sex == "男") {
                "1"
            } else {
                "0"
            }

            if (tepAvater != null) {
                uploadAvatarImage(tepAvater!!, object : Callback {
                    override fun onResponse(call: Call, response: Response) {
                        Log.d("picInfo", "头像图片上传成功")
                        val avaterImageOnNetName = response.body?.string()
                        if (avaterImageOnNetName != null) {
                            val user = User(UserConst.id, "", "", nickname, avaterImageOnNetName, intro, sex.toInt())
                            savePost(user)
                            UserConst.avatarImage = tepAvater
                        }
                    }

                    override fun onFailure(call: Call, e: IOException) {
                        Log.d("picInfo", "头像图片上传失败")

                    }
                }, "IMGUserAvater"+ Calendar.getInstance().time + ".jpeg")
            }
            else{
                val user = User(UserConst.id, "", "", nickname, null, intro, sex.toInt())
                savePost(user)
            }
        }

        // 返回
        binding.cancelButton.setOnClickListener {
            setResult(Activity.RESULT_CANCELED)
            finish()
        }
    }

    private val loginLauncher = registerForActivityResult(LoginContract()) { result ->

    }

    private fun savePost(user: User) {
        try {
            val request = Request.Builder()
                .url(NetworkSettings.USER + "update")
                .put(mapper.writeValueAsString(user).toRequestBody(mediaType)).build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    if (response.isSuccessful) {
                        val body = response.body
                        if (body != null) {
                            val restResponse = mapper.readValue(body.string(), RestResponse::class.java)
                            message.what = restResponse.code

                            Log.i("修改信息返回结果", "$user")
                            UserConst.nickname = user.nickname.toString()
                            if( user.intro != null) {
                                UserConst.intro = user.intro.toString()
                                UserConst.avatar = user.avatar.toString()

                            }
                            UserConst.sex = user.sex.toString().toInt()


                        } else {
                            message.what = ResponseCode.EMPTY_RESPONSE
                            Log.e("RESPONSE_BODY_EMPTY", response.message)
                        }

                    } else {
                        message.what = ResponseCode.SERVER_ERROR
                        Log.e("SERVER_ERROR", response.message)
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
        val intent = Intent()
        intent.putExtra("user", user)
        setResult(RESULT_OK, intent)
        finish()
    }
}